import { defineStore } from 'pinia'
import $axios from "../plugins/http"
import Cookie from '@/plugins/cookie'
import { useFriendPinia } from "./friend"

export const useUserPinia = defineStore('user', {
  // 推荐使用 完整类型推断的箭头函数
  state: () => ({
    /**
     * 该用户是否是第一次登录
     */
    isFirst: false,
    user: {
      // 用户的昵称
      nickName: '',
      // 用户的id号
      userId: '',
      // 用户的性别
      sex: '' as '男' | '女',
      age: 0,
      address: '',
      avatar: '',
      signature: '',
      bkImg: '',
      birthday: new Date(),
      areaCoord: [0, 0] as [number, number],
    } as Omit<User, 'remark'> & {
      bkImg: string;
      birthday: Date;
      areaCoord: [number, number];
    },
    // 申请添加我为好友的名单
    applicationList: new Map() as Map<string, {
      userInfo: Omit<User, 'remark' | 'userId'>;
      otherProto: {
        applyLan: string;
        isLoading: boolean;
        isLoadingRefuse: boolean;
        time: number;
      };
    }>,
  }),
  actions: {
    // 获取用户的个人信息
    async getUserInfo(): Promise<number> {
      return await $axios(
        ['/user/getUserInfo', 'post'],
        ({ user, isFirst, groups }): void => {
          const friendStore = useFriendPinia();
          this.isFirst = isFirst;
          if (!this.isFirst) {
            for (const key in this.user) {
              if (key === 'birthday') (this.user as any)[key] = new Date(user[key])
              else (this.user as any)[key] = user[key]
            }
            friendStore.groups.maxPage = groups.maxPage;
            friendStore.groups.value = groups.value
          }
        }
      )
    },
    // 设置用户的个人信息
    async setUserInfo(payload: {
      nickName: string;
      birthday: Date;
      sex: '男' | '女';
    }): Promise<number> {
      return await $axios(
        ['/user/setUserInfo', 'post', payload]
      )
    },
    // 判断用户是否第一次登录
    async isUserFirstLogin(): Promise<number> {
      return await $axios(
        ['/user/isFirstLogin', 'get'],
        ({ isFirst }) => this.isFirst = isFirst
      )
    },
    // 退出登录
    async signout(): Promise<number> {
      return await $axios(
        ['/user/logout'],
        () => Cookie.deleteCookie('token'),
      )
    },
    // 设置个性签名
    async changeSignature(payload: { signature: string }): Promise<number> {
      return await $axios(
        ['/user/updateUserInfo', 'patch', payload],
        () => this.user.signature = payload.signature,
      )
    },
    // 修改昵称
    async changeNickName(payload: { nickName: string }): Promise<number> {
      return await $axios(
        ['/user/updateUserInfo', 'patch', payload],
        () => this.user.nickName = payload.nickName,
      )
    },
    // 修改性别
    async changeSex(payload: { sex: '男' | '女' }): Promise<number> {
      return await $axios(
        ['/user/updateUserInfo', 'patch', payload],
        () => this.user.sex = payload.sex,
      )
    },
    // 修改生日
    async changeBirth(payload: { birthday: Date }): Promise<number> {
      return await $axios(
        ['/user/updateUserInfo', 'patch', payload],
        ({ age, birthday }) => {
          this.user.age = age;
          this.user.birthday = new Date(birthday);
        },
      )
    },
    // 修改区域
    async changeArea(payload: { area: string, areaCoord: [number, number] }): Promise<number> {
      return await $axios(
        ['/user/updateUserInfo', 'patch', payload],
        () => {
          this.user.address = payload.area;
          this.user.areaCoord = payload.areaCoord;
        }
      )
    },
    // 申请添加对方好友
    async applyAddFriend(payload: {
      selfId: string;
      otherId: string;
      addFriendProperty: {
        applyLan: string;
        remark: string;
        tag: string;
        disabledOtherLook: boolean;
        disabledSelfLook: boolean;
      },
    }): Promise<number> {
      return await $axios(
        ['/user/applyAddFriend', 'post', payload],
        () => {
          const friendStore = useFriendPinia();
          if (
            payload.addFriendProperty.tag &&
            !friendStore.groups.value.includes(payload.addFriendProperty.tag)
          )
            friendStore.groups.value.push(payload.addFriendProperty.tag)
        }
      )
    },
    // 是否同意对方的好友申请
    async isAgreeApply(payload: {
      selfId: string;
      otherId: string;
      isAgree: boolean;
      friendProperty?: {
        remark: string;
        group: string;
        disabledOtherLook: boolean;
        disabledSelfLook: boolean;
      },
    }, friend?: Omit<User, "userId" | "remark">): Promise<number> {
      return await $axios(
        ['/user/isAgreeApply', 'post', payload],
        async ({ initials }) => {
          this.applicationList.delete(payload.otherId);
          const friendStore = useFriendPinia();
          // 如果用户同意的话且该用户的分组没有包括该设置的分组的话
          if (
            payload.isAgree &&
            payload.friendProperty?.group &&
            !friendStore.groups.value.includes(payload.friendProperty?.group)
          )
            friendStore.groups.value.push(payload.friendProperty?.group!);
          if (payload.isAgree && friend) {
            if (friendStore.friends.has(initials))
              friendStore.friends.get(initials)?.value.set(payload.otherId, {
                isSendLoading: false,
                remark: payload.friendProperty?.remark!,
                avatar: friend.avatar,
              });
            else {
              const friendsArr = Array.from(friendStore.friends);
              if (initials !== '~') {
                const index: number = friendsArr.findIndex(item => item[0] > initials);
                friendsArr.splice(index, 0, [initials, {
                  value: new Map().set(payload.otherId, {
                    isSendLoading: false,
                    remark: payload.friendProperty?.remark!,
                    avatar: friend.avatar,
                  })
                }]);
              } else friendsArr.push([initials, {
                value: new Map().set(payload.otherId, {
                  isSendLoading: false,
                  remark: payload.friendProperty?.remark!,
                  avatar: friend.avatar,
                })
              }]);
              friendStore.friends = new Map(friendsArr);
            }
            if (friendStore.isRequFriendsManage)
              for (const [key, value] of friendStore.friendsManage) {
                if (key === 'all') {
                  if (value.noGroups?.isRequest) value.noGroups.friends.set(payload.otherId, {
                    ...friend,
                    ...payload.friendProperty!,
                  })
                } else if (value?.noGroups) {
                  if (key === 'disabledOtherLook') {
                    if (payload.friendProperty?.disabledOtherLook) {
                      value.noGroups.count!++;
                      value.noGroups.isRequest &&
                        value.noGroups.friends.set(payload.otherId, { ...friend, ...payload.friendProperty! })
                    }
                  }
                  else if (payload.friendProperty?.disabledSelfLook) {
                    value.noGroups.count!++;
                    value.noGroups.isRequest &&
                      value.noGroups.friends.set(payload.otherId, { ...friend, ...payload.friendProperty! })
                  }
                } else if (value?.groups) {
                  const nowGroup = payload.friendProperty?.group ? payload.friendProperty.group : '无分组';
                  if (value.groups?.has(nowGroup)) {
                    const groupData = value.groups.get(nowGroup)!;
                    groupData.count++;
                    groupData?.isRequest && groupData.friends.set(payload.otherId, { ...friend, ...payload.friendProperty! })
                  } else value.groups?.set(nowGroup, {
                    isRequest: true,
                    count: 1,
                    friends: new Map([[payload.otherId, { ...friend, ...payload.friendProperty! }]]),
                  })
                }
              }
          }
        },
      )
    },
  },
})